<template>
  <div class="configuration">
    <div class="left-set">
      <div class="node">
        <el-scrollbar class="custom-scrollbar">
          <div v-for="(item, index) in nodeComponents">
            <div class="title-collapse">{{ item.panelTitle }}</div>
            <el-row :gutter="20">
              <el-col :span="24" v-for="node in item.list">
                <div
                  class="node-comm"
                  :style="{ backgroundImage: 'url(' + node.icon + ')' }"
                  draggable="true"
                  @dragstart="onStart(node)"
                  @dragend="onEnd"
                >
                  {{ node.name }}
                </div>
              </el-col>
            </el-row>
            <el-divider v-if="index + 1 != nodeComponents.length" class="node-space" />
          </div>
        </el-scrollbar>
      </div>
    </div>
    <div style="width: 10px"></div>
    <el-scrollbar class="right-canvas custom-scrollbar" id="right-canvas">
      <div class="save-canvas">
        <el-select
          ref="canvasSizeSelect"
          style="width: 100px; margin-right: 10px"
          v-model="canvasSize"
          class="m-2"
          placeholder="画布倍率"
          @change="canvasSizeChange"
        >
          <el-option
            v-for="item in canvasOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        <el-button class="confirm-button" type="primary" @click="saveAllChain">{{
          langMsg?.save || "保存"
        }}</el-button>
      </div>
      <div
        class="flow-parent"
        id="flowcontainer"
        ref="flowcontainer"
        @drop="drop($event)"
        @dragover="allowDrop($event)"
        @click="flowcontainerSetting"
      >
        <div class="regular-start-node" id="regular-start-node">入口节点</div>
        <div
          class="node-comm"
          @contextmenu.prevent.stop="rightClick(node)"
          :style="getNodeStyle(node)"
          v-for="node in state.chain"
          :key="node.id"
          :id="node.id"
          @dblclick.stop="nodeDbClick(node)"
          :title="node.nodeName"
        >
          {{ node.nodeName }}
        </div>
      </div>
    </el-scrollbar>
    <MidNodeDialog
      v-if="clickNodeType == '3'"
      v-model="clickNodeType"
      :clickNodeInfo="currSelectNodeAtChain"
      @saveConfiguration="saveOrUpadate"
    >
    </MidNodeDialog>
    <BackNodeDialog
      v-if="clickNodeType == '2'"
      v-model="clickNodeType"
      :clickNodeInfo="currSelectNodeAtChain"
      @saveConfiguration="saveOrUpadate"
    >
    </BackNodeDialog>
    <rule-expression-dialog
      ref="expressionRef"
      v-if="clickNodeType == '1'"
      v-model="clickNodeType"
      :clickNodeInfo="currSelectNodeAtChain"
      @saveConfiguration="saveOrUpadate"
    ></rule-expression-dialog>
    <LineSettingDialog
      v-if="clickNodeType == 'line' && !isEnterLine"
      v-model="clickNodeType"
      :lineAttr="currentLineAttr"
      @setConnectionLabel="setConnectionLabel"
      @cancelLine="cancelLine"
    >
    </LineSettingDialog>
  </div>
</template>
<script setup lang="ts">
import FileSaver from "file-saver";
import {
  ready,
  newInstance,
  ContainmentType,
  EVENT_DRAG_STOP,
  EVENT_CONNECTION_CLICK,
  EVENT_CONNECTION_CONTEXTMENU,
} from "@jsplumb/browser-ui";
import { BezierConnector } from "@jsplumb/connector-bezier";
// import { StraightConnector } from '@jsplumb/core';
// import { deployChain, upateNodeRelation, getChainNodeDetail, getChainAllNode, deleteChainNode, saveChainNode, } from '@/api/RuleEngine'
import ruleNodeImg from "@/assets/images/rule-chain/rule-node.png";
import backNodeImg from "@/assets/images/rule-chain/back-node.png";
import ruleChainNodeImg from "@/assets/images/rule-chain/rule-chain-node.png";
import backValueNodeImg from "@/assets/images/rule-chain/back-value-node.png";
import midForwardNodeImg from "@/assets/images/rule-chain/mid-forward-node.png";
import { nodeTypeEnum } from "../const";
import { h, inject, nextTick, onMounted, reactive, ref, watch } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import RuleExpressionDialog from "./RuleExpressionDialog.vue";
import MidNodeDialog from "./MidNodeDialog.vue";
import BackNodeDialog from "./BackNodeDialog.vue";
import LineSettingDialog from "./LineSettingDialog.vue";

const props = defineProps({
  currChainId: {
    type: Number,
  },
});
const apis: any = inject("apis");
const langMsg: any = inject("langMsg");
//画布大小选择
let initWidth = 0;
let initHeight = 0;
const recordSize = ref(1);
const canvasSize = ref(1);
const canvasOptions = [
  {
    label: "1.0X",
    value: 1,
  },
  {
    label: "2.0X",
    value: 2,
  },
  {
    label: "4.0X",
    value: 4,
  },
];
const canvasSizeSelect = ref();
const canvasSizeChange = (val: any) => {
  initWidth = 0;
  initHeight = 0;
  state.chain.forEach((item: any) => {
    //拿到最大的长度
    if (item.webLeft > initWidth) initWidth = item.webLeft + 150;
    if (item.webTop > initHeight) initHeight = item.webTop + 40;
  });
  const el: any = document.getElementById("right-canvas");
  const flow: any = document.getElementById("flowcontainer");
  if (initWidth < el.clientWidth * val && initHeight < el.clientHeight * val) {
    flow.style.width = el.clientWidth * val + "px";
    flow.style.height = el.clientHeight * val + "px";
    recordSize.value = val;
  } else {
    canvasSize.value = recordSize.value;
    ElMessageBox({
      title: "Message",
      message: h("p", null, [
        h("span", null, "当前规则链不可调小画布倍率，小倍率会导致规则链超出画布"),
      ]),
    });
  }
};
//选中的节点或者线，用于控制设置面板显示
let isEnterLine = ref(false); //是否是从入口节点出来的连线
let clickNodeType = ref("0");

//当前选中的连线的属性
let currentLineAttr: any = ref({
  triggerType: 9,
  lineLabel: "",
  parentType: "",
});
//当前选中的连线
let currentConnection: any = ref(null);
//当前选中的规则链上的节点
let currSelectNodeAtChain: any = ref(null);

let oneAttrIsClick = ref(false);
let connectionIsClick = ref(false);
let flowIsClick = ref(false);
//左侧面板元组
//重写左侧节点
const nodeComponents = reactive([
  {
    panelTitle: langMsg?.nodetype || "节点类型",
    list: [
      {
        name: langMsg?.rulenode || "规则节点",
        type: nodeTypeEnum.ruleNode,
        icon: ruleNodeImg,
      },
      {
        name: langMsg?.middlewareforwardingnode || "中间件转发节点",
        type: nodeTypeEnum.midNode,
        icon: midForwardNodeImg,
      },
      // {
      //     name: '返回值节点', type: nodeTypeEnum.backValNode, icon: backValueNodeImg
      // },
    ],
  },
]);
const state: any = reactive({
  //需要拖拽的数据，拖拽后数据的顺序也会变化
  chain: [],
});

//从左侧拖到类型node
const currentItem = ref();
const startDragging = ref(true);

//拖动开始事件
const onStart = (item: any) => {
  currentItem.value = item;
  startDragging.value = true;
};
//拖动结束事件
const onEnd = () => {
  startDragging.value = false;
};
const newNode: any = ref({});
const drop = (event: any) => {
  event.preventDefault();

  let emptyNode: any = {};
  startDragging.value = false;
  //如果父元素不是最外层就，加入到最外层
  if (!event.target.className.includes("flow-parent")) {
    emptyNode.offsetTop = event.target.offsetTop - 50;
    emptyNode.offsetLeft = event.target.offsetLeft;
  }
  var temp: any = {
    //id: 'new-node',
    chainId: props.currChainId,
    parentId: 0,
    type: currentItem.value.type,
    webTop: emptyNode.offsetTop ? emptyNode.offsetTop : event.offsetY,
    webLeft: emptyNode.offsetLeft ? emptyNode.offsetLeft : event.offsetX,
    nodeName: currentItem.value.name,
    webIcon: getBackGround(currentItem.value.type),
    webWidth: 150,
    webHeight: 40,
  };
  newNode.value = JSON.parse(JSON.stringify(temp));
  currSelectNodeAtChain.value = JSON.parse(JSON.stringify(currentItem.value));
  clickNodeType.value = currentItem.value.type;
};

const rightClick = (node: any) => {
  deleteNode(node);
};

const nodeDbClick = (item: any) => {
  //点击element
  clickNodeType.value = item.type;
  currSelectNodeAtChain.value = item;
  connectionIsClick.value = false;
  oneAttrIsClick.value = true;
  flowIsClick.value = false;
};

//删除节点
const deleteNode = (node: any) => {
  nextTick(function () {
    ElMessageBox.confirm("确定删除" + node.nodeName + "吗?", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: langMsg?.cancel || "取消",
      type: "warning",
    }).then(async () => {
      let res = await apis?.deleteChainNode(node.id);
      let el: any = document.getElementById(node.id);
      instance.removeAllEndpoints(el);
      for (let i = state.chain.length - 1; i >= 0; i--) {
        if (state.chain[i].id === node.id) {
          state.chain.splice(i, 1);
        }
        if (state.chain[i] && state.chain[i].parentId == node.id) {
          //删除的时候如果有父ID指向这个要删除的节点，需要先把后续的节点的父ID删除了
          state.chain[i].parentId = 0;
          await apis?.upateNodeRelation([{ id: state.chain[i].id, parentId: 0 }]);
        }
      }
      clickNodeType.value = "0";
      ElMessage.success("节点删除成功！");
    });
  });
};
const allowDrop = (event: any) => {
  event.preventDefault();
};
const getBackGround = (type: any) => {
  let bgIcon;
  switch (type) {
    case "1":
      bgIcon = "rule-node.png";
      break;
    case "2":
      bgIcon = "back-value-node.png";
      break;
    case "3":
      bgIcon = "mid-forward-node.png";
      break;
    case "4":
      bgIcon = "rule-chain-node.png";
      break;
    case "5":
      bgIcon = "back-node.png";
      break;
  }
  return bgIcon;
};
const getNodeStyle = (node: any) => {
  let cssStyle =
    "top:" +
    node.webTop +
    "px;left:" +
    node.webLeft +
    "px;position:absolute;width:" +
    node.webWidth +
    "px;height:" +
    node.webHeight;
  switch (node.type) {
    case "1":
      cssStyle += "px;background-image:" + "url(" + ruleNodeImg + ")";
      break;
    case "2":
      cssStyle += "px;background-image:" + "url(" + backValueNodeImg + ")";
      break;
    case "3":
      cssStyle += "px;background-image:" + "url(" + midForwardNodeImg + ")";
      break;
    case "4":
      cssStyle += "px;background-image:" + "url(" + ruleChainNodeImg + ")";
      break;
    case "5":
      cssStyle += "px;background-image:" + "url(" + backNodeImg + ")";
      break;
  }
  return cssStyle;
};
//节点加入到state-line上
const saveOrUpadate = async (data: any) => {
  //新增节点，页面新增元素并同时保存到数据库
  //元素el的属性设置
  let res;
  try {
    if (data.id) {
      //编辑
      res = await apis?.saveChainNode(data);
    } else {
      //新增
      //delete newNode.value.id
      let params = { ...newNode.value, ...data };
      res = await apis?.saveChainNode(params);
    }
    ElMessage.success("节点信息保存成功");
    if (!data.id) {
      //新建节点成功，把这个节点加入到state.line线上
      state.chain.push(newNode.value);
    }
    let resData = res.data.data;
    //新建节点成功，给这个节点设置端点
    for (let i = 0; i < state.chain.length; i++) {
      let item = state.chain[i];
      if (!item.id) {
        //新增的节点
        state.chain[i] = { ...item, ...resData };
        nextTick(function () {
          const el = document.getElementById(resData.id);
          if (
            currentItem.value.type == nodeTypeEnum.midNode ||
            currentItem.value.type == nodeTypeEnum.backNode
          ) {
            instance.addEndpoint(el, {
              target: true,
              source: false,
              anchor: "Left",
              ...defaultEndpoint,
            });
          } else {
            instance.addEndpoint(el, {
              target: true,
              source: false,
              anchor: "Left",
              ...defaultEndpoint,
            });
            instance.addEndpoint(el, {
              target: false,
              source: true,
              anchor: "Right",
              ...defaultEndpoint,
            });
          }
        });
        break;
      }
      if (item.id == resData.id) {
        state.chain[i] = resData;
        break;
      }
    }
  } catch (err: any) {
    ElMessage({
      message: err.data.msg || "服务器异常，请稍后再试",
      grouping: true,
      type: "error",
    });
  }
};

const saveAllChain = async () => {
  //保存链
  await apis?.deployChain(props.currChainId);
  ElMessage.success("保存成功");
};
const cancelLine = (cont: any) => {
  if (!cont) instance.deleteConnection(currentConnection.value);
};
const setConnectionLabel = async (attr: any) => {
  //设置线上的label，如果有真假值时假值线设红色
  nextTick(async () => {
    state.chain.forEach(async (item: any) => {
      if (item.id == currentConnection.value.targetId) {
        await apis?.upateNodeRelation([
          {
            id: item.id,
            parentId: currentConnection.value.sourceId,
            ...attr,
          },
        ]);
        ElMessage.success("线属性设置成功");
        currentConnection.value.getOverlay("myLabel").setLabel(attr.lineLabel);
        item.lineLabel = attr.lineLabel;
        item.triggerType = attr.triggerType;
        item.parentId = currentConnection.value.sourceId;
        if (item.triggerType == 0) {
          instance.setColor(currentConnection.value, "red");
        } else {
          instance.setColor(currentConnection.value, color2);
        }
      }
    });
  });
};
// let flowAttrOption = reactive({ name: '' })
const flowcontainerSetting = () => {
  flowIsClick.value = true;
  connectionIsClick.value = false;
  oneAttrIsClick.value = false;
};
// const setFlowAtrr = () => { }
// const exportJson = () => {
//     const blob = new Blob([JSON.stringify(state.chain, null, 2)], { type: 'application/json' })
//     FileSaver.saveAs(blob, flowAttrOption.name)
// }
const importJson = () => {
  setTimeout(() => {
    //先把所有节点遍历布局，并在节点上添加上端点
    state.chain.forEach((item: any) => {
      let el = document.getElementById(item.id);
      if (item.type == nodeTypeEnum.midNode || item.type == nodeTypeEnum.backNode) {
        instance.addEndpoint(el, {
          uuid: "LEFT" + item.id,
          target: true,
          source: false,
          anchor: "Left",
          ...defaultEndpoint,
        });
      } else {
        instance.addEndpoint(el, {
          uuid: "LEFT" + item.id,
          target: true,
          source: false,
          anchor: "Left",
          ...defaultEndpoint,
        });
        instance.addEndpoint(el, {
          uuid: "RIGHT" + item.id,
          target: false,
          source: true,
          anchor: "Right",
          ...defaultEndpoint,
        });
      }
      //拿到最大的长度
      if (item.webLeft > initWidth) initWidth = item.webLeft + 150;
      if (item.webTop > initHeight) initHeight = item.webTop + 40;
    });
    const el: any = document.getElementById("right-canvas");
    const flow: any = document.getElementById("flowcontainer");
    if (initWidth / el.clientWidth > 1 || initHeight / el.clientHeight > 1) {
      let beilv =
        Math.ceil(initWidth / el.clientWidth) > Math.ceil(initHeight / el.clientHeight)
          ? Math.ceil(initWidth / el.clientWidth)
          : Math.ceil(initHeight / el.clientHeight);
      canvasSize.value = beilv > 2 ? 4 : beilv;
      recordSize.value = canvasSize.value;
      flow.style.width = el.clientWidth * canvasSize.value + "px";
      flow.style.height = el.clientHeight * canvasSize.value + "px";
    }

    //把数据连在固定的端点
    state.chain.forEach((item: any) => {
      if (item.firstNodeFlag == 1) {
        //连接入口节点
        instance.connect({
          uuids: ["RIGHT-regular-start-node", "LEFT" + item.id],
          source: document.getElementById("regular-start-node"),
          target: document.getElementById(item.id),
          paintStyle: { stroke: color2, strokeWidth: 3 },
          connector: {
            type: BezierConnector.type,
            options: { curviness: 63 },
          },
        });
      }
      if (document.getElementById(item.parentId)) {
        let config = {
          uuids: ["RIGHT" + item.parentId, "LEFT" + item.id],
          source: document.getElementById(item.parentId),
          target: document.getElementById(item.id),
          connector: {
            type: BezierConnector.type,
            options: { curviness: 63 },
          },
          paintStyle: {
            stroke: item.triggerType == 0 ? "red" : color2,
            strokeWidth: 3,
          },
          connectorStyle: { stroke: color2, strokeWidth: 3 },
          // overlays: [
          //     {
          //         type: 'Label',
          //         options: { id: 'myLabel', label: tar.label || '', location: 0.5 }
          //     }
          // ],
        };
        instance.connect(config);
      }
    });
  }, 50);
};
//jsplumb
//1、实例化jsplubms
let instance: any;
//参数属性
var exampleDropOptions = {
  tolerance: "touch",
  hoverClass: "dropHover",
  activeClass: "dragActive",
};
var color2 = "#09A4F0";
var defaultEndpoint = {
  paintStyle: { fill: "#fff" }, //端点的颜色
  hoverPaintStyle: {
    fill: "#FCFD3C",
    stroke: "#FCFD3C",
    cursor: "crosshair",
  },
  //scope: 'green',
  endpoint: {
    //端点类型,连线两端的端点类型
    type: "Dot",
    options: {
      // width:15,
      // height:15,
      radius: 6,
      hoverClass: {},
    },
  },
  //connectorStyle: { stroke: color2, strokeWidth: 1 },
  connectorHoverStyle: {
    stroke: "#FCFD3C",
  },
  maxConnections: 16, //最多几个连线
  dropOptions: exampleDropOptions,
  connectionsDetachable: true, //允许链接分离从el上，没作用
  deleteEndpointsOnDetach: true, //删除el元素的时候删除端点
};
const getDetailById: any = async (id: any) => {
  let res = await apis?.getChainNodeDetail(id);
  return res.data.data;
};

const initJsplumb = () => {
  ready(() => {
    const elm: any = document.getElementById("flowcontainer");
    instance = newInstance({
      connectionsDetachable: true, //不可通过鼠标拆卸
      //拖动的配置
      dragOptions: {
        cursor: "pointer",
        zIndex: 2000,
        containment: ContainmentType.parentEnclosed,
      }, //不能超出父级
      hoverClass: "",
      paintStyle: { stroke: color2, strokeWidth: 3 },
      connector: {
        type: BezierConnector.type,
        options: { curviness: 63, gap: 6 },
      },
      connectionOverlays: [
        //链接线上的覆盖物
        {
          type: "Arrow", //箭头
          options: { location: 1 },
        },
        {
          type: "Label",
          options: { id: "myLabel", label: "", location: 0.5 },
        },
      ],
      container: elm, //容器
    });
    //暂停绘制，初始化
    instance.batch(() => {
      instance.bind(EVENT_DRAG_STOP, (p: any) => {
        //node 拖动结束
        var temp: any = {
          top: p.elements[0].pos.y,
          left: p.elements[0].pos.x,
        };
        state.chain.forEach((item: { id: any; webTop: any; webLeft: any }) => {
          if (item.id == p.el.id) {
            item.webTop = temp.top;
            item.webLeft = temp.left;
            apis
              ?.upateNodeRelation([
                { id: item.id, webTop: item.webTop, webLeft: item.webLeft },
              ])
              .then(() => {
                // ElMessage.success('节点位置保存成功')
              });
          }
        });
      });
      instance.bind("connection", async (conn: any) => {
        //连线建立时触发
        //一是界面手动连线触发，2是查询出组态规则遍历成画布时触发
        if (conn.sourceId == "regular-start-node") {
          //规则链入口节点加入标识firstNodeFlag
          for (let i = 0, len = state.chain.length; i < len; i++) {
            let item = state.chain[i];
            if (item.id == conn.targetId) {
              if (item.parentId) {
                //targetId有parentId就不能连线了
                instance.deleteConnection(conn);
                break;
              }
              //若是新链接的线，弹框type设置为line
              if (!item.firstNodeFlag) {
                item.firstNodeFlag = 1;
                let res = await apis?.upateNodeRelation([
                  {
                    id: item.id,
                    firstNodeFlag: item.firstNodeFlag,
                    lineLabel: "始终触发",
                    triggerType: 9,
                  },
                ]);
              }
              //连接入口节点的线不显示输入标签的输入框
              instance.removeOverlay(conn.connection, "myLabel");
              break;
            }
          }
        } else {
          for (let i = 0, len = state.chain.length; i < len; i++) {
            let item = state.chain[i];
            if (item.id == conn.targetId) {
              if (!item.parentId) {
                //新增
                let parentObj = await getDetailById(conn.sourceId);
                //若是新连接的线，弹框type设置为line
                console.log(parentObj);
                currentLineAttr.value = {
                  id: null,
                  lineLabel: "",
                  triggerType: 9,
                  parentType: parentObj?.type,
                };
                currentConnection.value = conn.connection;
                clickNodeType.value = "line";
              }
              if (item.parentId && item.parentId != conn.sourceId) {
                instance.deleteConnection(conn.connection);
              } else {
                conn.connection.getOverlay("myLabel").setLabel(item.lineLabel || "");
              }
              break;
            }
          }
        }
      });
      instance.bind(EVENT_CONNECTION_CONTEXTMENU, (conn: any, e: any) => {
        e.preventDefault();
        //右击连线时触发，删除
        ElMessageBox.confirm("确定删除吗?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: langMsg?.cancel || "取消",
          type: "warning",
        })
          .then(() => {
            instance.deleteConnection(conn);
            //删除state.chain里面的线
            state.chain.forEach((item: any) => {
              if (item.id == conn.targetId) {
                delete item.lineLabel;
                delete item.triggerType;
                delete item.parentId;
                item.firstNodeFlag = 0;
                apis?.upateNodeRelation([
                  {
                    id: item.id,
                    parentId: 0,
                    firstNodeFlag: 0,
                    lineLabel: "",
                    triggerType: 9,
                  },
                ]);
              }
            });
            clickNodeType.value = "0";
          })
          .catch(() => {});
      });
      instance.bind(EVENT_CONNECTION_CLICK, (conn: any) => {
        currentConnection.value = conn;
        currentLineAttr.value.id = conn.targetId;
        currentLineAttr.value.triggerType = 9;
        currentLineAttr.value.parentType = "";
        currentLineAttr.value.lineLabel = conn.getOverlay("myLabel").getLabel();

        if (conn.sourceId == "regular-start-node") {
          isEnterLine.value = true;
          return;
        } else {
          isEnterLine.value = false;
        }
        state.chain.forEach(async (item: any) => {
          if (item.id == conn.targetId) {
            let parentObj = await getDetailById(item.parentId);
            currentLineAttr.value.id = item.id;
            currentLineAttr.value.lineLabel = item.lineLabel;
            currentLineAttr.value.triggerType = item.triggerType;
            currentLineAttr.value.parentType = parentObj?.type;
            clickNodeType.value = "line";
          }
        });
      });
    });
    //固定开始节点
    instance.addEndpoint(document.getElementById("regular-start-node"), {
      uuid: "RIGHT-regular-start-node",
      target: false,
      source: true,
      anchor: "Right",
      ...defaultEndpoint,
      maxConnections: 1,
    });
    instance.registerConnectionType("custom", {
      connectorStyle: { stroke: "red", strokeWidth: 3 },
      paintStyle: { stroke: "red", strokeWidth: 3 },
      connector: {
        type: BezierConnector.type,
        options: { curviness: 63, gap: 6 },
      },
      connectionOverlays: [
        //链接线上的覆盖物
        {
          type: "Arrow", //箭头
          options: { location: 1 },
        },
        {
          type: "Label",
          options: { id: "myLabel", label: "", location: 0.5 },
        },
      ],
    });
  });
};
watch(
  () => props.currChainId,
  async () => {
    if (props.currChainId) {
      let res = await apis?.getChainAllNode(props.currChainId);
      state.chain = res.data.data || [];
      nextTick(() => {
        importJson();
      });
    }
  },
  {
    immediate: true,
    deep: true,
  }
);
//clear画布
// const clearCanvas = () => {
//     //也应该在这里把panel组件的数据也清除掉
//     //删除全部连接线\端点
//     clickNodeType.value = '0'
//     state.chain = []
//     instance.reset()
//     creatDiv()
//     instance.addEndpoint(document.getElementById('regular-start-node'), { uuid: 'RIGHT-regular-start-node', target: false, source: true, anchor: 'Right', ...defaultEndpoint })
// }
// const creatDiv = () => {
//     const parent = document.getElementById('flowcontainer')
//     const enterDoc = document.createElement('div')
//     enterDoc.textContent = '入口节点'
//     enterDoc.style.height = '40px'
//     enterDoc.style.width = '150px';
//     enterDoc.style.position = 'absolute'
//     enterDoc.style.textAlign = 'center'
//     enterDoc.style.lineHeight = '40px'
//     enterDoc.style.left = '40px'
//     enterDoc.style.top = '40px'
//     enterDoc.style.border = '1px solid silver'
//     enterDoc.style.cursor = 'pointer'
//     enterDoc.id = 'regular-start-node'
//     enterDoc.className = 'regular-start-node'
//     parent.appendChild(enterDoc)
// }
defineExpose({
  state,
  clickNodeType,
});
//init
// const contextmenu = ref()
onMounted(() => {
  initJsplumb();
  //失去焦点时关闭右击菜单
});
</script>
<style lang="scss" scoped>
.configuration {
  width: 100%;
  height: 100%;
  display: flex;
  user-select: none;

  .node-comm {
    cursor: pointer;
    height: 40px;
    line-height: 40px;
    text-align: center;
    background-size: 100% 100%;
    background-repeat: no-repeat;
    text-overflow: ellipsis;
    overflow: hidden;
    white-space: nowrap;
  }

  .left-set {
    width: 300px;
    display: flex;
    flex-direction: column;

    .node {
      padding: 20px;
      height: 100%;
      background-size: 100% 100%;
      background-repeat: no-repeat;
      background-image: url("@/assets/images/rule-chain/border.png");

      .title-collapse {
        width: 64px;
        height: 22px;
        font-size: 16px;
        font-family: PingFangSC-Medium, PingFang SC;
        font-weight: 500;
        color: #09a4f0;
        line-height: 22px;
      }

      .el-row {
        margin: 0 !important;

        .el-col {
          box-sizing: border-box;
        }
      }

      .node-space {
        border-top: 1px solid #093d74;
      }

      .el-col {
        height: 40px;
        margin-top: 20px;
      }

      .el-space {
        width: 100%;
      }
    }

    .setting {
      display: flex;
      flex-direction: column;
      flex: 1;
      background-size: 100% 100%;
      background-repeat: no-repeat;
      background-image: url("@/assets/images/rule-chain/border-setting.png");

      :deep(.title) {
        padding-top: 2%;
        height: 10%;
        display: flex;
        justify-content: center;
        align-items: center;
      }

      :deep(.content) {
        position: relative;
        flex: 1;
        padding: 10px;
        box-sizing: border-box;
      }

      :deep(.button-div) {
        position: relative;
        text-align: center;
        width: 100%;
        padding: 0 10px 20px;
        box-sizing: border-box;

        .cancel-button {
          width: 100%;
          background: rgba(255, 255, 255, 0);
          color: #3790e2;
          border-radius: 3px;
          border: 1px solid;
          border-image: linear-gradient(
              80deg,
              rgba(22, 127, 229, 1),
              rgba(104, 195, 243, 0),
              rgba(55, 144, 226, 1)
            )
            1 1;
        }

        .confirm-button {
          width: 100%;
          background: #09a4f0;
          border-radius: 3px;
          color: #00062a;
        }
      }

      .el-select,
      .el-input_inner {
        width: 100%;
      }
    }
  }

  .right-canvas {
    flex: 1;
    background-size: 100% 100%;
    background-repeat: no-repeat;
    background-image: url("@/assets/images/rule-chain/canvas-border.png");

    :deep(.el-scrollbar__view) {
      height: 100%;
      width: 100%;
    }

    .save-canvas {
      margin-right: 0;
      height: 30px;
      padding: 5px;
      display: flex;
      justify-content: right;

      .confirm-button {
        background: #09a4f0;
        border-radius: 3px;
        color: #00062a;
      }
    }
  }

  .flow-parent {
    position: relative;
    height: calc(100% - 30px);
    width: 100%;

    .regular-start-node {
      height: 40px;
      width: 150px;
      position: absolute;
      text-align: center;
      line-height: 40px;
      left: 40px;
      top: 40px;
      border: 1px solid silver;
      cursor: pointer;
    }
  }

  // :deep(.el-dialog__header) {
  //     position: absolute !important;
  //     z-index: 9999;
  //     height: 32px !important;
  //     background-color: red;
  // }
}
</style>
